<?php

/**
 * Check a GUID corresponds to an entity
 * @param int $guid
 * @param (yes|no|NULL) $enabled
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_is_entity($guid, $enabled='yes'){	
	$query= blg_dbschema_select_entities(array('guid' => $guid, NULL, 'enabled' => $enabled));
	$query= blg_dbschema_query_buid($query, 'count');
	$result= blg_dbschema_select($query);
	$result= (int)$result->{0}['result'];
	return ($result>0);		
}

/**
 * Delete an entity
 * @param $entity_guid
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_entity_delete($entity_guid){
	$query= blg_dbschema_query_buid(blg_dbschema_update_entities(
		array('guid' => $entity_guid),
		array('enabled' => 'no')
	));
	$result= blg_dbschema_update($query);	
	return $result->sucess;
}

/**
 * Update entity access id
 * @param $entity_guid
 * @param $new_access_id
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_entity_update_access_id($entity_guid, $new_access_id){
	$query= blg_dbschema_query_buid(blg_dbschema_update_entities(
		array('guid' => $entity_guid),
		array('access_id' => $new_access_id)
	));
	$result= blg_dbschema_update($query);	
	return $result->sucess;
}

/**
 * Update entity access id
 * @param $entity_guid
 * @param $new_access_id
 * @return Boolean
 * @author Pablo
 * @since 1.0
 */
function blg_entity_update_time_updated($entity_guid, $time=NULL){
	if($time=NULL)
		$time= time();
		
	$query= blg_dbschema_query_buid(blg_dbschema_update_entities(
		array('guid' => $entity_guid),
		array('time_updated' => $time)
	));
	$result= blg_dbschema_update($query);	
	return $result->sucess;
}

/**
 * Update entity last action time
 * @param $guid User GUID
 * @param $time
 * @return (int|FALSE) Returns previous last action, FALSE in case of failure
 * @author Pablo
 * @since 1.0
 */
function blg_entity_last_action($entity_guid, $time=NULL){
	if(empty($time))
		$time= time();
	
	//Select actual time
	$result= blg_dbschema_select(blg_dbschema_query_buid(blg_dbschema_select_entities(array('guid' => $guid), array('last_action'))));
	$last_action= (int)$result->{0}['last_action'];
	
	//Update
	$query= blg_dbschema_query_buid(blg_dbschema_update_entities(
		array('guid' => $guid),
		array('last_action' => $time)
	));
	$result= blg_dbschema_update($query);
	
	if($result->success){
		return $last_action;
	}
	
	return FALSE;
}